package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class FilePictureUpolad extends PictureUploadTemp{


    //文件校验
    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile= (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile==null, ErrorCode.PARAMS_ERROR, "文件不能为空");

        //1.校验文件大小
        long fileSize=multipartFile.getSize();
        final  long ONE_MB=1024*1024;
        ThrowUtils.throwIf(fileSize>2*ONE_MB,ErrorCode.PARAMS_ERROR,"上传图片大小不能超过2MB");
        //校验文件后缀
        String fileSuffix= FileUtil.getSuffix(multipartFile.getOriginalFilename());
        //允许上传的文件后缀列表
        final List<String> ALLOW_FORMAT_LIST= Arrays.asList("png","jpg","jpeg","gif","webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"上传图片格式错误");
    }

    //获取原始文件名
    @Override
    protected String getOriginalFileName(Object inputSource) {
        MultipartFile multipartFile= (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {

        MultipartFile multipartFile= (MultipartFile) inputSource;
        multipartFile.transferTo(file);

    }

//    @Override
//    protected UploadPictureResult buildResult(String originalFileName, File file, String uploadFilePath, ImageInfo imageInfo) {
//
//        UploadPictureResult uploadPictureResult=new UploadPictureResult();
//        uploadPictureResult.setUrl(uploadFilePath);
//        uploadPictureResult.setPicName(originalFileName);
//        uploadPictureResult.setPicSize(file.length());
//        uploadPictureResult.setPicWidth(imageInfo.getWidth());
//        uploadPictureResult.setPicHeight(imageInfo.getHeight());
//        uploadPictureResult.setPicScale(imageInfo.getWidth()*1.0/imageInfo.getHeight());
//        uploadPictureResult.setPicFormat(imageInfo.getFormat());
//        uploadPictureResult.setPicColor(imageInfo.getAve());
//
//
//
//        return null;
//    }
}
